import { Directive, DirectiveBinding } from 'vue';

function throttle(func: Function, wait: number) {
    let timeout: ReturnType<typeof setTimeout> | null = null;
    let lastExecution = 0;
  
    return function (this: any, ...args: any[]) {
      const now = Date.now();
      const remainingTime = wait - (now - lastExecution);
  
      if (remainingTime <= 0) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        lastExecution = now;
        func.apply(this, args);
      } else if (!timeout) {
        timeout = setTimeout(() => {
          lastExecution = Date.now();
          timeout = null;
          func.apply(this, args);
        }, remainingTime);
      }
    };
  }

  interface ElType extends HTMLElement {
    __throttleHandler__: () => void;
  }
  
  const throttleDirective: Directive = {
    mounted(el: ElType, binding: DirectiveBinding) {
      if (typeof binding.value !== 'function') {
        console.warn('v-throttle expects a function as the value');
        return;
      }
  
      // 使用指令参数设置节流时间，如果没有设置则使用默认值 1000ms
      const wait = binding.arg ? parseInt(binding.arg) : 1000;
  
      el.__throttleHandler__ = throttle(binding.value, wait);
      el.addEventListener('click', el.__throttleHandler__);
    },
    beforeUnmount(el: ElType) {
      el.removeEventListener('click', el.__throttleHandler__);
    },
  };
  
  export default throttleDirective;
    